import json,re,random,io,sys,requests,time

from django.shortcuts import render
from django.views import View
from django.http import JsonResponse,QueryDict,HttpResponse
from django.views.decorators.csrf import csrf_exempt

from py2neo import Graph,Node,Relationship
# Create py2neo connection
graph = Graph(host='localhost',auth=('neo4j','123'))
# Create your views here.

@csrf_exempt
def registerUser(request):
    global graph
    username = eval(request.body.decode()).get('username')
    password = eval(request.body.decode()).get('password')

    a = Node("My_User", username=username, createDate=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),password=password)
    try:
        graph.create(a)
        return JsonResponse({"status": "ok","success": True, "username": username})
    except:
        return JsonResponse({"status": "error","success": False })

@csrf_exempt
def logIn(request):
    global graph
    username = eval(request.body.decode()).get('username')
    password = eval(request.body.decode()).get('password')

    sql = "MATCH (u:My_User{username:'"+username+"',password:'"+password+"'}) RETURN count(u) as u"
    count = graph.run(sql).data()
    if username == "admin":
        authority = "admin"
    else:
        authority = "user"
    if count[0]["u"] > 0:
        return JsonResponse({"status": "ok","success": True,"username":username,"currentAuthority":authority ,"type":"account"})
    else:
        return JsonResponse({"status": "error","success": False,"type":"account"})


